/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bittorent.like;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import bittorent.like.IP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.JFileChooser;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
/**
 *
 * @author tuongvanthanh
 */
public class Mainform extends javax.swing.JFrame {

    /**
     * Creates new form Mainform
     */
    private ArrayList<String> hashes;
    
    
    public Mainform() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jFileChooser1 = new javax.swing.JFileChooser();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jtfDuongDanFileTorrent = new javax.swing.JTextField();
        jbtMoFile = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jlbSoLuongChunk = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jlbChunkDangTai = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jlbSoChunkHoanTat = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jpsbarTrangThai = new javax.swing.JProgressBar();
        jbtMoFileHoanTat = new javax.swing.JButton();
        jbtThoat = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jbtnChiaSeChunk = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jtfDuongDanFileChunk = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();

        jMenuItem1.setText("jMenuItem1");

        jMenu1.setText("jMenu1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bittorent-like 1.0");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Torrent file"));

        jLabel1.setText("Mở file .torrent :");

        jtfDuongDanFileTorrent.setEnabled(false);

        jbtMoFile.setText("Mở ...");
        jbtMoFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtMoFileActionPerformed(evt);
            }
        });

        jLabel3.setText("Số lượng chunk :");

        jlbSoLuongChunk.setText("sl");

        jLabel5.setText("Chunk đang tải :");

        jlbChunkDangTai.setText("cur chunk");

        jLabel7.setText("Hoàn tất :");

        jlbSoChunkHoanTat.setText("numb");

        jLabel9.setText("chunk");

        jButton1.setText("Bắt đầu tải...");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(36, 36, 36)
                                .addComponent(jtfDuongDanFileTorrent, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jbtMoFile, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(jlbSoLuongChunk)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1)))
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel7))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbSoChunkHoanTat)
                            .addComponent(jlbChunkDangTai))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(68, 68, 68)
                                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(5, 5, 5)
                                .addComponent(jLabel9)))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtfDuongDanFileTorrent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtMoFile))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jlbSoLuongChunk)
                    .addComponent(jButton1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jlbChunkDangTai))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(jlbSoChunkHoanTat)
                            .addComponent(jLabel9)))
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        jLabel2.setText("Trạng thái :");

        jbtMoFileHoanTat.setText("Mở file hoàn tất ");
        jbtMoFileHoanTat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtMoFileHoanTatActionPerformed(evt);
            }
        });

        jbtThoat.setText("Thoát");
        jbtThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtThoatActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Chia sẻ chunk"));

        jbtnChiaSeChunk.setText("Chia sẻ chunk");
        jbtnChiaSeChunk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnChiaSeChunkActionPerformed(evt);
            }
        });

        jLabel4.setText("Đường dẫn file chunk :");

        jtfDuongDanFileChunk.setEnabled(false);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addComponent(jtfDuongDanFileChunk, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtnChiaSeChunk)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jtfDuongDanFileChunk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jbtnChiaSeChunk))
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jMenu2.setText("File");
        jMenu2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu2ActionPerformed(evt);
            }
        });

        jMenuItem2.setText("Thêm torrent");
        jMenu2.add(jMenuItem2);

        jMenuItem3.setText("Thoát");
        jMenu2.add(jMenuItem3);

        jMenuBar1.add(jMenu2);

        jMenu3.setText("Options");

        jMenuItem4.setText("jMenuItem4");
        jMenu3.add(jMenuItem4);

        jMenuItem5.setText("jMenuItem5");
        jMenu3.add(jMenuItem5);

        jMenuBar1.add(jMenu3);

        jMenu4.setText("Help");

        jMenuItem6.setText("About");
        jMenu4.add(jMenuItem6);

        jMenuBar1.add(jMenu4);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 6, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jbtMoFileHoanTat)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtThoat, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jpsbarTrangThai, javax.swing.GroupLayout.PREFERRED_SIZE, 405, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(165, 165, 165)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jpsbarTrangThai, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtThoat)
                    .addComponent(jbtMoFileHoanTat))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenu2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu2ActionPerformed
        // TODO add your handling code here:
        
        this.dispose();
    }//GEN-LAST:event_jMenu2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        // load file .map và broadcast thông tin đi
        Thread t=Thread.currentThread();
        System.out.println(t.getName());
        ArrayList<String> nodes=new ArrayList<>();// luu danh sach cac node
        // 
        File f=new File("."+"\\map\\nodes.map");
        System.out.print(f.getAbsolutePath()+"\n");
        System.out.print(f.isFile());
        try{
           FileReader read=new FileReader(f);
           BufferedReader buf=new BufferedReader(read);
           String data="";
           while((data=buf.readLine())!=null){
               nodes.add(data);
           }
        }catch(IOException ex){
           Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        // danh sach ip address va port cua cac may trong mang
        ArrayList<IP> ips=new ArrayList<IP>();
        String[] addcut=new String[2];// luu ipaddress va port
        String[] ipcut=new String[5];//luu cac octet
        for(int i=0;i<nodes.size();i++){
            addcut=nodes.get(i).split(" ");// cat string thanh ipaddr va port
            IP ip=new IP();
            ipcut=addcut[0].split("\\.");// lay cac octet trong ipaddr
            ip.setOctet1(Integer.parseInt(ipcut[0]));
            ip.setOctet2(Integer.parseInt(ipcut[1]));
            ip.setOctet3(Integer.parseInt(ipcut[2]));
            ip.setOctet4(Integer.parseInt(ipcut[3]));
            ip.setPort(Integer.parseInt(addcut[1]));
            
            ips.add(ip);// add va list
        }
        
        // gui broadcast
        int time=0;
        while(time<hashes.size()){// gui broadcast va nhan tuan tu goi tin 
            String chunk=hashes.get(time);// lay gia tri hash trong hashes
            try {
                // tao UDPsocket
                DatagramSocket udpsocket=new DatagramSocket();
                // chuyen ma hash thanh mang byte
                byte[] brsend=new byte[1024];
                brsend=chunk.getBytes();
                DatagramPacket pksend;
                DatagramPacket pkrecv;
                // duyet danh sach cac ip
                for(int i=0;i<ips.size();i++){
                    String ip=ips.get(i).getOctet1()+"."+ips.get(i).getOctet2()+"."+ips.get(i).getOctet3()+"."+ips.get(i).getOctet4();
                    //byte[] bytip=new byte[]{ips.get(i).getOctet1(),ips.get(i).getOctet2(),ips.get(i).getOctet3(),ips.get(i).getOctet4()};
                    //InetAddress ipclient=InetAddress.getByAddress(ip,new byte[]{ips.get(i).getOctet1(),ips.get(i).getOctet2(),ips.get(i).getOctet3(),ips.get(i).getOctet4()})
                   byte oct1=(byte)ips.get(i).getOctet1();
                   byte oct2=(byte)ips.get(i).getOctet2();
                   byte oct3=(byte)ips.get(i).getOctet3();
                   byte oct4=(byte)ips.get(i).getOctet4();
                   byte[] byt=new byte[]{oct1,oct2,oct3,oct4};
                   
                   InetAddress ipclient=InetAddress.getByAddress(ip, byt);
                   // gui hash cua chunk time qua cho may khac
                   pksend=new DatagramPacket(brsend,brsend.length,ipclient,ips.get(i).getPort());
                   // send broadcast 
                   udpsocket.send(pksend);
                   
                   System.out.println("\nGet chunk send:"+pksend.getData()+" to: "+ipclient+ " port:"+pksend.getPort());
                    
//                   String rcvpk;
//                   byte[] rcvbuf=new byte[1024];
//                  pkrecv=new DatagramPacket(rcvbuf, rcvbuf.length);
//                  udpsocket.receive(pkrecv);
//                  rcvpk=new String(pkrecv.getData(), 0, pkrecv.getLength());
//                    System.out.println("Get chunk recive: "+rcvpk);
//                    
//                  if(rcvpk.equals("got")){// nhan duoc goi tin bao ben kia co chunk nay
//                      // gui thong diep "please send" cho ben co chunk nay
//                      String plz="please send";
//                      byte[] plzsend=plz.getBytes();
//                      pksend=new DatagramPacket(plzsend, plzsend.length, ipclient, ips.get(i).getPort());
//                      udpsocket.send(pksend);
//                      ////
//                      System.out.println("Get chunk send 'please send':"+pksend.getData());
//   
//                      
//                  }
//                  break;
                           
                }
                
            } catch (SocketException ex) {
                Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
            }catch(IOException ex){
                ex.printStackTrace();
            }
            
          
            
            
            
            time++;
        }
                
        
//        for(int i=0;i<ips.size();i++){
//            System.out.println(ips.get(i).getOctet1()+"."+ips.get(i).getOctet2()+"."+
//                    ips.get(i).getOctet3()+"."+ips.get(i).getOctet4());
//            System.out.println(ips.get(i).getPort());
//            System.out.println("--------------------------");
//        }
//        
        //InetAddre ip=InetAddress.
       // InetAddress ip= InetAddress.getByAddress(, addr)
        // duyệt mảng hashfile, chuyển giá trị hash này sang mảng byte và gủi giá trị này đi
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jbtMoFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtMoFileActionPerformed
        // TODO add your handling code here:
        // mo file .torrent
        // luu thong tin hash file vào trong 1 mảng
        jFileChooser1.showOpenDialog(null);
        File f=jFileChooser1.getSelectedFile();
        String duoi=f.getName();
        duoi=duoi.substring(duoi.lastIndexOf("."), duoi.length());
        System.out.println(duoi);
        jtfDuongDanFileTorrent.setText(jFileChooser1.getSelectedFile().getAbsolutePath());
        try {
            //int size=(int)f.length();
            //jlbKichThuocFile.setText(String.valueOf(size));
            // doc file
            FileReader read=new FileReader(f);
            String data="";
            BufferedReader buf=new BufferedReader(read);
            hashes=new ArrayList<>();
            while((data=buf.readLine())!=null){
                hashes.add(data);
            }
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }catch(IOException ex){
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // set label sl chunk
        jlbSoLuongChunk.setText(String.valueOf(hashes.size()));
        int i=0;
        while(i<hashes.size()){
            System.out.println(hashes.get(i));
            i++;
        }
    }//GEN-LAST:event_jbtMoFileActionPerformed

    private void jbtThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtThoatActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jbtThoatActionPerformed

    private void jbtnChiaSeChunkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnChiaSeChunkActionPerformed
        // TODO add your handling code here:
        // load file .chunk len.
        // load danh sach cac file chunk len
        
        //jFileChooser1.showOpenDialog(null);
      File f=null;
//      jFileChooser1.getSelectedFile();
        JFileChooser fcs=new JFileChooser();
        fcs.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fcs.showOpenDialog(this);
        f=fcs.getSelectedFile();
        ArrayList<String> hashshares=new ArrayList<String>();
        File[] fs=null;
        if(f.isDirectory()){
            fs=new File[f.listFiles().length];
            fs=f.listFiles();
        }else{
            fs=new File[1];
            fs[0]=f;
        }
        MessageDigest  md=null;
        try {
            md=MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // tinh toan hash 
        byte[] b=null;
        for(int i=0;i<fs.length;i++){
            try {
                b=Files.readAllBytes(fs[i].toPath());
                String hash=(new HexBinaryAdapter()).marshal(md.digest(b));
                hashshares.add(hash);
            } catch (IOException ex) {
                Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
        
         //        for(int i=0;i<hashshares.size();i++){
            //            System.out.println(hashshares.get(i));
            //        }
        
        try {
           
            while(true){
            
                // mo socket lang nghe broadcast 
                DatagramSocket socket=new DatagramSocket();
                String stRcv;
                String stSend;
                byte[]rcvbuf=new byte[1024];
                DatagramPacket rcvpkt=new DatagramPacket(rcvbuf,rcvbuf.length);
                // nhan packet broadcast
                socket.receive(rcvpkt);
                stRcv=new String(rcvpkt.getData(), 0,rcvpkt.getLength());
                // duyet mang hash de so khop gia tri voi goi tin broadcast
                System.out.println("Co chunk Nhận: "+stRcv);
                
                int j=0;
                for(int i=0;i<hashshares.size();i++){
                    if(hashshares.get(i).equals(stRcv)){// co giu chunk cua may yeu cau 
                       j=i;
                       stSend="got";
                       byte[] sendbuf=new byte[1024];
                       sendbuf=stSend.getBytes();
                       DatagramPacket sendpkt=new DatagramPacket(sendbuf,sendbuf.length,rcvpkt.getAddress(),rcvpkt.getPort());
                       // gui thong diep "got" cho may yeu cau
                       socket.send(sendpkt);
                       // nhan thong diep "please send"
                        System.out.println("Co chunk GửI:"+stSend);
                       
                       break;
                       //break;
                    }    
                }
                
                    
                    break;
                    
            }        
                    
                    
                    // neu goi tin nhan duoc co data trung voi gia tri hash 
                    // cat thanh cac manh 1024 byte
                    // truyen cac manh nay qua cho may yeu cau
        } catch (SocketException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Mainform.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbtnChiaSeChunkActionPerformed

    private void jbtMoFileHoanTatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtMoFileHoanTatActionPerformed
        // TODO add your handling code here:
//        String ad="192.168.1.1";
//        String[] a;
//        a=ad.split("\\.");
//        for(int i=0;i<a.length;i++){
//            System.out.println(a[i]);
//        }
    }//GEN-LAST:event_jbtMoFileHoanTatActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Mainform.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Mainform().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JButton jbtMoFile;
    private javax.swing.JButton jbtMoFileHoanTat;
    private javax.swing.JButton jbtThoat;
    private javax.swing.JButton jbtnChiaSeChunk;
    private javax.swing.JLabel jlbChunkDangTai;
    private javax.swing.JLabel jlbSoChunkHoanTat;
    private javax.swing.JLabel jlbSoLuongChunk;
    private javax.swing.JProgressBar jpsbarTrangThai;
    private javax.swing.JTextField jtfDuongDanFileChunk;
    private javax.swing.JTextField jtfDuongDanFileTorrent;
    // End of variables declaration//GEN-END:variables
}
